//
//  HMNetworkTools.swift
//  06-Swift网络工具抽取
//
//  Created by HM on 15/12/28.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import AFNetworking


/// 请求方法
///
/// - GET:  get
/// - POST: post
enum YYRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class YYNetworkTools: AFHTTPSessionManager {
    
    // 单例
    static let sharedTools: YYNetworkTools = {
        let instance = YYNetworkTools()
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    // (response: AnyObject?, error: NSError?)->()
    // 定义请求完成的回调的别名
    typealias YYRequestCallBack = (response: AnyObject?, error: NSError?)->()
    
    /// 请求数据
    ///
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数
    /// - parameter finished:   请求成功或者失败的回调
    func request(method: YYRequestMethod = .GET, urlString: String, parameters:AnyObject?, finished:YYRequestCallBack){
        
        // dataTaskWithHttp 是写在 .m 文件里面的
        // 对应在 Swift 中的，就是 private 修饰的方法
        
        // 定义请求成功的闭包
        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            finished(response: responseObject, error: nil)
        }
        
        // 定义请求失败的闭包
        let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(response: nil, error: error)
        }
        
        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}

//oauth 登陆获取数据
extension YYNetworkTools{
    
    //请求 accessToken
    func loadAccessToken(code: String, finished:YYRequestCallBack){
        //请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        let parameter = [
            "client_id":WB_APPKEY,
            "client_secret":WB_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_REDIRECTURI
        ]
        
        //发送请求
        request(.POST, urlString: urlString, parameters: parameter, finished: finished)
        
    }
    
    //请求个人信息
    func loadUserAccount(accessToken: String,uid: String,finished: YYRequestCallBack){
        //请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        //请求参数
        let params = [
            "access_token":accessToken,
            "uid":uid
        ]
        request(urlString: urlString, parameters: params, finished: finished)
    }
    
}





